package com.ldxiwxr.common.utils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

import static com.ldxiwxr.common.constant.RedisConstant.CODE;


/**
 * 验证码工具类
 *
 * @author SuBanxia
 */
@Component
public class KaptchaUtils {
    @Resource
    private DefaultKaptcha defaultKaptcha;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 生成验证码
     * @param response 响应
     * @throws IOException IO异常
     */
    public void kaptchaProduce(HttpServletResponse response) throws IOException {
        // --------------------------- 生成验证码开始 -----------------------------
        // 获取验证码的文本内容
        String text = defaultKaptcha.createText();
        // 将验证码内容存储到Redis中
        redisTemplate.opsForValue().set(CODE, text);
        // 得到图片
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            // 通过流的形式将验证码传输出去
            outputStream = response.getOutputStream();
            // 输出流输出图片，格式为jpg
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
        // --------------------------- 生成验证码结束 -----------------------------
    }
}
